<!--
 * @轮子的作者: 轮子哥
 * @Date: 2023-08-29 15:34:18
 * @LastEditTime: 2023-12-07 17:48:12
-->
<template>
    <!--左侧房源筛选-->
    <div class="lefMain" v-show="!isFastSearch">
        <!--左侧1-->
        <span class="leftTop">
            <span style="font-size: 18px;white-space: nowrap;font-weight: 600;color: #7a8df1;">{{ $t('text.House.l161')
            }}</span>
            <DialogLayout19>
                <span class="df" @click="isShowAddHouse">
                    <img class="addImg" src="../../assets/images/add.svg">
                    <div style="font-size: 13px;white-space: nowrap;">{{ $t('text.House.l162') }}</div>
                </span>
            </DialogLayout19>
        </span>

        <!--左侧2-->
        <div class="leftTopInput">
            <img class="img1" src="../../assets/images/search2.png" />
            <input :placeholder="$t('text.House.l163')" class="leftTop2Input" v-model="communityOrId"
                @focus="isSearchClick = true" v-if="searchData.houseClass != 2">
            <input :placeholder="$t('text.House.l303')" class="leftTop2Input" v-model="realName"
                v-if="searchData.houseClass == 2">
            <div class="searchDiv4" v-if="isSearchClick" @click="searchClick">{{ $t('text.House.l299') }}</div>
            <span v-if="isSearchClick" @click="isSearchClick = false; communityOrId = ''; realName = ''"
                class="searchCancel">{{
                    $t('text.House.l300')
                }}</span>
        </div>
        <!--列表-->
        <div v-if="isSearchClick && communityOrId != ''">
            <div v-for="item in community" v-bind:key="item" class="searchDiv1">
                <img class="searchDiv2" src="../../assets/images/search2.png" />
                <div style="flex: 1;" @click="communityOrId = item.name; searchClick()">
                    <div>{{ item.name }}</div>
                    <div class="searchDiv3">NO.{{ item.id }}</div>
                </div>
            </div>
        </div>
        <!--历史记录-->
        <div v-if="isSearchClick && communityOrId == ''">
            <div class="searchDiv5">{{ $t('text.House.l301') }}</div>
            <div v-for="item in communityLocal" v-bind:key="item" class="searchDiv1" style="gap:5px">
                <div style="flex: 1;" @click="communityOrId = item.name; searchClick()">
                    <div>{{ item.name }}</div>
                    <div class="searchDiv3"></div>
                </div>
            </div>
        </div>

        <!--左侧3-->
        <div v-if="isLoad && !isSearchClick">
            <div class="leftTop2" style="padding: 2px 10px;" v-if="searchData.houseClass != 2">
                <div class="df">
                    <img class="img2" src="../../assets/images/icon.png" />
                    <div class="items">
                        <RadioSelectPlate @returnData="setData" @clearData="clearData"></RadioSelectPlate>
                    </div>
                </div>
            </div>
            <div class="leftTop2" v-for="(item, index1) in houseSelect" v-bind:key="item">
                <div class="df" v-for="(s, index2) in item" v-bind:key="s">
                    <img class="img2" src="../../assets/images/icon.png" />
                    <div class="items">
                        <RadioSelect :leftText="s.title" :selectList="s.isArea ? areaList : getSelectData(s.dictionaryKey)"
                            :searchKey="s.searchKey" :isShowTitle="s.isShowTitle" :isShowSerach1="s.isShowSerach1"
                            :isShowSerach2="s.isShowSerach2" :inputEndText="s.inputEndText" :isReset="isReset"
                            :isShowBottom="s.isShowBottom" :isMultiple="s.isMultiple" @returnData="setData"
                            :isResetList="isResetList" :max="s.max" :min="s.min" @clearData="clearData"
                            :fastSearch="s.fastSearch" :isRange="s.isRange" :orgTreeList="orgTreeList"
                            :isSingle="s.isSingle" :isArea="s.isArea" :ref="'RadioSelect' + index1 + index2">
                        </RadioSelect>
                    </div>
                </div>
            </div>

        </div>

        <!--左侧4-->
        <div class="lb" v-if="!isSearchClick">
            <div class="lb-f">
                <span class="sl-l" @click="openFastSearch">{{ $t('text.House.l167') }}</span>
                <DialogLayout20 :paramJson="searchData" :moduleType="searchData.houseClass"
                    :type="String(searchData.houseClass)" :fastSearchList="fastSearchList">
                    <span @click="getReturnFastSearch">{{ $t('text.House.l168') }}</span>
                </DialogLayout20>
            </div>
            <div class="lb-r" @click="reset">
                <span>{{ $t('text.House.l169') }}</span>
            </div>
        </div>

    </div>

    <!--左侧保存搜索-->
    <div class="lefMain" v-show="isFastSearch && isLoad">
        <div class="s8">
            <div class="s2" v-for="item in fastSearchConvert" v-bind:key="item" @click="setFastSearch(item.paramJson)">
                <div class="s3">
                    <div class="s4">{{ item.title }}&ensp;</div>
                    <div class="s5" @click="deleteFastSearch(item.id)"><img src="../../assets/images/mClose.svg" class="s6">
                    </div>
                </div>
                <div style="height: inherit;overflow: auto;">
                    <div class="s7" v-for="child in JSON.parse(item.paramJson).original" v-bind:key="child">
                        {{ child.title + ": " + child.value }}
                    </div>
                </div>
            </div>
        </div>
        <button class="s1" @click="isFastSearch = !isFastSearch">{{ $t('text.House.l204') }}</button>
    </div>

    <!--右侧房源列表-->
    <div class="rightMain">
        <!--右侧顶部导航-->
        <div class="rightTop">
            <div class="f1">
                <div class="mapDiv" @click="this.$router.push({ path: './map', replace: true })">
                    <img class="mapImg" src="../../assets/images/mapIcon.svg">
                    {{ $t('text.House.l170') }}
                </div>
            </div>
            <TimePageNavList :timeNavList="timeNavList.data" :defaultClick="timeNavList.defaultClick"
                @returnData="setHouseType"></TimePageNavList>

            <div class="f1" style="display: flex;justify-content: flex-end;">
                <CommonSelectRouter :dataList="sortRouterList.data" :default="sortRouterList.default" ref="child1"
                    :myStyles="{ width: 'auto', background: 'none' }" @returnData="setSort" isShowSortImg>
                </CommonSelectRouter>
            </div>
        </div>
        <!--右侧房源数据列表-->
        <div class="rightContain">
            <HouseList :data="houseList" v-if="searchData.houseClass != 2" :index="searchData.houseClass">
            </HouseList>
            <HouseList :data="houseList" v-if="searchData.houseClass == 2" isNewHouse :index="searchData.houseClass">
            </HouseList>

            <!--底部分页-->
            <div class="setPage">
                <el-pagination v-model:current-page="searchData.page" v-model:page-size="searchData.size"
                    :page-sizes="[10, 15, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>

    </div>
</template>
    
<script>
import { houseSelect1, houseSelect2, houseSelect3 } from "../../itemList"
import RadioSelect from "../../components/select/RadioSelect.vue"
import {
    findPageByParam,
    getDropdownBoxData,
    searchFindPage,
    searchDel,
    areaFindTreeAll,
    orgTreeByCurrUser,
    newsFindPageParam,
    communityFindAll,
} from "../../http/api"
import { ElMessage } from "element-plus"
import TimePageNavList from "@/components/navigation/TimePageNavList.vue"
import DialogLayout19 from "@/components/dialogLayout/DialogLayout19.vue"
import RadioSelectPlate from "@/components/select/RadioSelectPlate.vue"
import DialogLayout20 from "@/components/dialogLayout/DialogLayout20.vue"
import CommonSelectRouter from "@/components/input/CommonSelectRouter.vue"
export default {
    name: "HouseManage",
    components: {
        RadioSelect,
        TimePageNavList,
        DialogLayout19,
        RadioSelectPlate,
        DialogLayout20,
        CommonSelectRouter,
    },
    data() {
        return {
            timeNavList: {
                defaultClick: this.$t("text.HomeView.l12"),
                data: [this.$t("text.HomeView.l12"), this.$t("text.HomeView.l13"), this.$t("text.HomeView.l14")],
            },
            houseSelect: houseSelect1,
            sortRouterList: {
                default: this.$t("text.House.l171"),
                data: [
                    { id: 1, name: this.$t("text.House.l171") },
                    { id: 2, name: this.$t("text.House.l172") },
                    { id: 3, name: this.$t("text.House.l173") },
                    { id: 4, name: this.$t("text.House.l174") },
                    { id: 5, name: this.$t("text.House.l175") },
                    { id: 6, name: this.$t("text.House.l176") },
                ],
            },
            searchData: {
                houseClass: 0,
                label: null,
                role: null,
                roomNumber: null,
                page: 1,
                size: 20,
            },
            searchDataDefault: {
                houseClass: 0,
                label: null,
                role: null,
                roomNumber: null,
                page: 1,
                size: 20,
            },
            isLoad: false,
            loadCount: 0,
            dictionaryTree: {},
            isReset: false,
            houseList: [],
            total: 0,
            isFastSearch: false,
            fastSearchList: [],
            fastSearchConvert: [],
            areaList: [],
            orgTreeList: [],
            communityOrId: "",
            isSearchClick: false,
            community: [],
            communityLocal: [],
            communityCopy: [],
            realName: "",
            isResetList: false,
            dictionaryTreeCopy: {},
        }
    },
    mounted() {
        //初始化查询
        this.search()
        this.loadCount = 0
        //初始化字典数据请求
        getDropdownBoxData().then((res) => {
            if (res !== undefined) {
                this.dictionaryTreeCopy = JSON.parse(JSON.stringify(res))
                this.dictionaryTree = res

                areaFindTreeAll().then((res) => {
                    if (res !== undefined) {
                        this.areaList = [{ dictName: this.$t('text.Common.l12'), id: "-1" }, ...res]
                        this.loadCount = this.loadCount + 1
                    }
                }).catch()

                orgTreeByCurrUser().then((res) => {
                    if (res !== undefined) {
                        this.orgTreeList = res
                        this.loadCount = this.loadCount + 1
                    }
                }).catch()
            }
        }).catch()
    },
    methods: {
        //获取字典数据
        getSelectData(key) {
            const data = this.dictionaryTree[key]
            if (data != undefined) {
                return this.dictionaryTree[key]
            } else {
                return [{ dictName: this.$t('text.Common.l12'), dictValue: "-1", }]
            }
        },

        //拼接单个子组件返回来的条件值
        setData(obj) {
            const keys = Object.keys(obj)
            //是否是入住时间
            if (keys.includes('abidesTime_EQ')) {
                obj = { abidesTime_BEGIN: this.reduceTime(obj.abidesTime_EQ) }
            }
            this.searchData = { ...this.searchData, ...obj }
            //类型跟分类进行联动
            if (keys.length > 0 && keys[0] == "houseType_EQ") {
                switch (obj.houseType_EQ) {
                    case "0":
                        this.dictionaryTree.houseDetailsType = this.dictionaryTreeCopy.houseDetailsType.filter(
                            (v) => v.typeCode === "houseDwellType" || v.dictValue === "-1"
                        )
                        break
                    case "1":
                        this.dictionaryTree.houseDetailsType = this.dictionaryTreeCopy.houseDetailsType.filter(
                            (v) => v.typeCode === "houseVillaType" || v.dictValue === "-1"
                        )
                        break
                    case "2":
                        this.dictionaryTree.houseDetailsType = this.dictionaryTreeCopy.houseDetailsType.filter(
                            (v) => v.typeCode === "houseWriteType" || v.dictValue === "-1"
                        )
                        break
                    case "3":
                        this.dictionaryTree.houseDetailsType = this.dictionaryTreeCopy.houseDetailsType.filter(
                            (v) => v.typeCode === "houseShopsType" || v.dictValue === "-1"
                        )
                        break
                    case "4":
                        this.dictionaryTree.houseDetailsType = this.dictionaryTreeCopy.houseDetailsType.filter(
                            (v) => v.typeCode === "houseGarageType" || v.dictValue === "-1"
                        )
                        break
                }
                this.isResetList = !this.isResetList
            }
        },

        //子组件选择了不限，进行删除指定字段
        clearData(obj, s) {
            //类型与分类进行联动
            if (s && s.typeCode == "houseType") {
                if (s.dictValue == "-1") {
                    this.dictionaryTree.houseDetailsType = this.dictionaryTreeCopy.houseDetailsType
                    this.isResetList = !this.isResetList
                } else {
                    obj = { ...obj, houseDetailsType_EQ: "" }
                }
            }
            const objKeys = Object.keys(obj)
            this.searchData = Object.keys(this.searchData).reduce((acc, key) => {
                if (!objKeys.includes(key)) {
                    acc[key] = this.searchData[key]
                }
                return acc
            }, {})
        },

        //清除只返回值
        clearData2(obj) {
            const objKeys = Object.keys(obj)
            return Object.keys(this.searchData).reduce((acc, key) => {
                if (!objKeys.includes(key)) {
                    acc[key] = this.searchData[key]
                }
                return acc
            }, {})
        },

        //计算时间
        reduceTime(day) {
            const now = new Date();
            const days = Number(day);
            const diff = days * 24 * 60 * 60 * 1000;
            const newDate = new Date(now.getTime() - diff);
            return newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate();
        },

        //打开快速搜索
        openFastSearch() {
            searchFindPage({ moduleType: this.searchData.houseClass }).then((res) => {
                if (res !== undefined) {
                    this.fastSearchConvert = res
                    this.isFastSearch = !this.isFastSearch
                }
            }).catch()
        },

        //获取查询列表改动的标题和显示值
        getReturnFastSearch() {
            let temp = []
            this.houseSelect.forEach((element, index1) => {
                element.forEach((item, index2) => {
                    const childRef = this.$refs['RadioSelect' + index1 + index2]
                    if (childRef && childRef.length > 0 && childRef[0].returnFastSearch() != null) {
                        temp.push(childRef[0].returnFastSearch())
                    }
                });
            });
            this.fastSearchList = temp
            return temp
        },

        //保存搜索里面，根据快速搜索取出来的值进行匹配赋值,
        setFastSearch(obj) {
            obj = JSON.parse(obj)
            let select = JSON.parse(JSON.stringify(this.houseSelect))
            select.forEach(element => {
                element.forEach(element2 => {
                    const temp = obj.original.filter(v => v.searchKey === element2.searchKey)
                    if (temp.length > 0)
                    element2.fastSearch = temp[0].value
                });
            });
            this.houseSelect = select
            this.isFastSearch = !this.isFastSearch
            this.searchData = obj.params
        },


        //删除快速保存
        deleteFastSearch(id) {
            searchDel({ id: id }).then((res) => {
                if (res !== undefined) {
                    ElMessage.success({
                        showClose: true,
                        message: this.$t("text.House.l206"),
                        type: "success",
                    })
                } else {
                    ElMessage.error({
                        showClose: true,
                        message: this.$t("text.House.l205"),
                        type: "error",
                    })
                }
            }).catch()
        },

        //选择排序
        setSort(index) {
            let obj
            switch (index) {
                case 1:
                    obj = { createTime_ORDER: "DESC" }
                    break
                case 2:
                    obj = { followTime_ORDER: "DESC" }
                    break
                case 3:
                    obj = { price_ORDER: "DESC" }
                    break
                case 4:
                    obj = { price_ORDER: "ASC" }
                    break
                case 5:
                    obj = { floorArea_ORDER: "DESC" }
                    break
                case 6:
                    obj = { floorArea_ORDER: "ASC" }
                    break
            }
            this.searchData = {
                ...this.clearData2({ createTime_ORDER: "", followTime_ORDER: "", price_ORDER: "", floorArea_ORDER: "" }),
                ...obj,
            }
        },

        //切换房屋类型
        setHouseType(index) {
            let temp
            switch (index) {
                case 0:
                    temp = { houseClass: 0 }
                    this.searchData = { ...this.searchDataDefault, ...temp }
                    this.houseSelect = houseSelect1
                    break
                case 1:
                    temp = { houseClass: 1 }
                    this.searchData = { ...this.searchDataDefault, ...temp }
                    this.houseSelect = houseSelect2
                    break
                case 2:
                    temp = { houseClass: 2 }
                    this.searchData = { ...this.searchDataDefault, ...temp }
                    this.houseSelect = houseSelect3
                    break
            }
            this.communityOrId = ""
        },

        //搜索数据
        search() {
            if (this.searchData.houseClass != 2) {
                findPageByParam(this.searchData)
                    .then((res) => {
                        if (res !== undefined) {
                            this.houseList = res.dataList
                            this.total = res.total
                        }
                    })
                    .catch()
            } else {
                let temp = JSON.parse(JSON.stringify(this.searchData))
                temp.pageNo = this.searchData.page
                temp.pageSize = this.searchData.size
                newsFindPageParam(this.searchData).then((res) => {
                    if (res !== undefined) {
                        this.houseList = res.dataList
                        this.total = res.total
                    }
                }).catch()
            }
        },

        //重置
        reset() {
            this.searchData = {
                houseClass: this.searchData.houseClass,
                label: null,
                role: null,
                roomNumber: null,
                page: 1,
                size: 10,
            }
            this.isReset = !this.isReset
        },
        handleSizeChange(val) {
            this.searchData.size = val
            this.search()
        },
        handleCurrentChange(val) {
            this.searchData.page = val
            this.search()
        },
        //点击顶部搜索
        searchClick() {
            if (this.communityOrId != "") {
                let obj = { communityOrId: this.communityOrId }
                this.setData(obj)
                let records = JSON.parse(localStorage.getItem("communityOrId")) || []
                // 添加新记录到数组开头
                records.unshift({ name: this.communityOrId })
                // 如果记录数超过 20 个，删除最旧的记录
                if (records.length > 20) {
                    records.pop()
                }
                // 保存更新后的记录数组到 localStorage
                localStorage.setItem("communityOrId", JSON.stringify(records))
            }
            this.isSearchClick = !this.isSearchClick
        },
    },
    watch: {
        searchData: {
            handler() {
                this.search()
            },
        },
        loadCount: {
            handler() {
                if (this.loadCount >= 2) {
                    this.isLoad = true
                }
            },
        },
        //监听最顶部搜素框的值
        communityOrId() {
            if (this.communityOrId != "" && this.communityCopy.length == 0) {
                //相当于初始化，只有打开点击输入了才请求一次
                communityFindAll()
                    .then((res) => {
                        if (res !== undefined) {
                            this.communityCopy = res
                            this.community = res.filter((v) => v.name.includes(this.communityOrId))
                        }
                    })
                    .catch()
            }
            if (this.communityOrId != "") {
                //模糊匹配过滤
                this.community = this.communityCopy.filter((v) => v.name.includes(this.communityOrId))
            }
            if (this.communityOrId == "") {
                this.clearData({ communityOrId: "" })
            }
        },
        isSearchClick() {
            //获取缓存
            let records = JSON.parse(localStorage.getItem("communityOrId")) || []
            this.communityLocal = records
        },
        realName() {
            if (this.realName != "") {
                this.setData({ name_LIKE: this.realName })
            } else {
                this.clearData({ name_LIKE: "" })
            }
        },
    },
    computed: {},
}
</script>
    
<style scoped>
.leftTopInput {
    display: flex;
    width: 100%;
    position: relative;
    padding-top: 10px;
}

.searchDiv5 {
    text-align: left;
    font-size: 14px;
    color: gray;
    padding: 5px;
}

.searchDiv4 {
    display: flex;
    z-index: 2;
    font-size: 12px;
    color: #6698ff;
    white-space: nowrap;
    padding-top: 6px;
    padding-left: 10px;
}

.searchDiv3 {
    color: #b0b0b0;
    border-bottom: 1px solid #eee;
    padding-bottom: 3px;
}

.searchDiv2 {
    width: 15px;
    height: 15px;
    z-index: 1;
    padding-right: 5px;
}

.searchDiv1 {
    display: flex;
    align-items: center;
    text-align: left;
    padding: 5px 15px;
    font-size: 13px;
}

.searchCancel {
    font-size: 12px;
    color: #6698ff;
    white-space: nowrap;
    padding-top: 6px;
    padding-left: 10px;
}

.df {
    display: flex;
    align-items: center;
    margin-top: 2px;
    margin-bottom: 2px;
}

.lefMain {
    min-width: 310px;
    width: 310px;
    padding: 15px;
    overflow: auto;
    background: white;
    margin-bottom: 30px;
    margin-right: 5px;
    box-shadow: 1px 10px 30px 4px #e9e9e9;
}

.leftTop {
    color: #6698ff;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.leftTop2 {
    border: 1px solid #cecece;
    border-radius: 5px;
    padding: 10px;
    margin-top: 10px;
    position: relative;
}

.leftTop2Input {
    outline: none;
    width: inherit;
    height: 25px;
    border: 1px solid rgb(220, 223, 230);
    padding-left: 23px;
    padding-right: 20px;
    background-color: rgb(242, 242, 242);
    border-radius: 5px;
    font-size: 12px;
}

.leftTop2Input:focus {
    border: 1px solid #6698ff;
}

.img2 {
    left: 15px;
    width: 15px;
    height: 15px;
    top: 17px;
    z-index: 1;
}

.img1 {
    left: 7px;
    width: 15px;
    height: 15px;
    top: 17px;
    z-index: 1;
    position: absolute;
}

.addImg {
    width: 15px;
    height: 15px;
    padding-right: 3px;
}

.mapImg {
    height: 17px;
    width: 17px;
    padding-right: 3px;
}

.mapDiv {
    display: flex;
    padding-left: 15px;
    font-size: 13px;
    color: #6698ff;
    align-items: center;
    width: fit-content;
}

.leftTop2-1 {
    display: flex;
    align-items: center;
    font-size: 12px;
    margin-top: 15px;
    line-height: 18px;
    color: gray;
}

.img2 {
    width: 22px;
    height: 22px;
}

.items {
    margin-left: 15px;
    padding-top: 6px;
    padding-bottom: 6px;
    font-size: 12px;
    color: gray;
    border-bottom: 1px solid rgb(224, 224, 224);
    width: 100%;
}

.lb {
    color: #6698ff;
    display: flex;
    justify-content: space-between;
    font-size: 13px;
    position: absolute;
    bottom: 40px;
    width: 300px;
}

.sl-l::after {
    content: "|";
    padding-left: 5px;
    padding-right: 5px;
}

.rightMain {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #f8f8f8;
}

.rightContain {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;
    background: white;
    margin: 10px 30px 30px 25px;
    position: relative;
    box-shadow: 1px 5px 10px 4px #e9e9e9;
}

.rightList {
    padding: 5px 15px;
}

.rightList:hover {
    background-color: #f0f0f0;
}

.rightTop {
    display: flex;
    padding-top: 12px;
    align-items: center;
    justify-content: space-between;
    padding-left: 10px;
    padding-right: 17px;
}

.f1 {
    flex: 1;
}

.lb-f {
    display: flex;
    align-items: center;
}

.lb-r {
    position: absolute;
    right: 0;
}

.s1 {
    background: rgb(242, 242, 242);
    border: none;
    outline: none;
    width: 100%;
    padding: 4px 0;
    border-radius: 5px;
    margin: 10px 0;
}

.s1:hover {
    color: #6698ff;
    border: 1px solid #6698ff;
    border-radius: 7px;
}

.s2 {
    border: 1px solid #ddd;
    border-radius: 10px;
    padding: 10px;
    font-size: 12px;
    text-align: left;
    width: 120px;
    height: 150px;
    overflow: hidden;
}

.s3 {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #ddd;
    padding-bottom: 3px;
}

.s6 {
    width: 10px;
    height: 10px;
}

.s6:hover {
    width: 15px;
    height: 15px;
}

.s8 {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.setPage {
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #eee;
    padding: 10px
}
</style>